#!/usr/bin/env node
"use strict";

const fs = require("fs");
const shell = require("shelljs");
const path = require("path");
const getOneReport = require("./getOneReport");

const pwd = process.cwd();
if (isGitRepo(pwd)) {
  getOneReport(pwd);
} else {
  const folderArr = getAbsolutePathesUnderAbsolutePath(pwd);
  folderArr.forEach((path) => {
    if (isGitRepo(path)) {
      getOneReport(path);
    } else {
      const nextLayerFolderArr = getAbsolutePathesUnderAbsolutePath(path);
      nextLayerFolderArr.forEach((path) => {
        if (isGitRepo(path)) {
          getOneReport(path);
        } else {
        }
      });
    }
  });
}

function getAbsolutePathesUnderAbsolutePath(currentPath) {
  const dirArr = fs.readdirSync(currentPath);
  const pathArr = [];

  for (let i = 0; i < dirArr.length; i++) {
    if (dirArr[i].indexOf(".") !== 0) {
      const absolutePath = path.join(currentPath, dirArr[i]);
      if (!fs.statSync(absolutePath).isFile()) {
        pathArr.push(absolutePath);
      }
    }
  }

  return pathArr;
}

function isGitRepo(dir) {
  const gitResErr = shell.exec(`git -C ${dir} rev-parse`, {
    silent: true,
  }).stderr;
  if (gitResErr === "") {
    return true;
  } else {
    return false;
  }
}
